package com.appbee.cm.client.modular.presenter;

import javax.inject.Inject;

import com.appbee.core.client.modular.IModul;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SingleSelectionModel;
import com.google.gwt.view.client.TreeViewModel;

public class ModulTreeViewModel implements TreeViewModel
{
	private final SingleSelectionModel<IModul> selectionModel = new SingleSelectionModel<IModul>();
	private final ModulGroups modulGroups;

	@Inject
	public ModulTreeViewModel(ModulGroups modulGroups)
	{
		this.modulGroups = modulGroups;
	}

	@Override
	public <T> NodeInfo<?> getNodeInfo(T value)
	{
		if (value == null)
		{
			return new DefaultNodeInfo<ModulGroup>(
					new ListDataProvider<ModulGroup>(modulGroups.getList()),
					new ModulGroupCell());

		}
		if (!(value instanceof ModulGroup))
			return null;

		ModulGroup modulGroup = (ModulGroup) value;

		return new DefaultNodeInfo<IModul>(new ListDataProvider<IModul>(
				modulGroup.getModuls()),
				new ModulCell(), selectionModel, null);
	}

	@Override
	public boolean isLeaf(Object value)
	{
		if (value == null)
			return false;
		if (value instanceof IModul)
			return true;
		return false;
	}

	public SingleSelectionModel<IModul> getSelectionModel()
	{
		return selectionModel;
	}

	public class ModulCell extends AbstractCell<IModul>
	{

		@Override
		public void render(	Context context,
		                   	IModul value,
							SafeHtmlBuilder sb)
		{
			sb.appendEscaped(value.getName());
		}

	}

	public class ModulGroupCell extends AbstractCell<ModulGroup>
	{

		@Override
		public void render(Context context, ModulGroup value, SafeHtmlBuilder sb)
		{
			sb.appendEscaped(value.getName());
		}

	}

}
